﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AutoCreatTables.Business
{
    /// <summary>
    /// 自动分析与创建表
    /// </summary>
    public class AutoAnalyseAndCreatTables
    {

        /// <summary>
        /// 后台扫描线程
        /// </summary>
        private Thread threadScan = null;

        /// <summary>
        /// 开始扫描并创建表
        /// </summary>
        public void StartAnalyseAndCreatTables()
        {
            this.threadScan = new Thread(new ThreadStart(this.AnalyseAndCreatTables));
            this.threadScan.IsBackground = true;
            this.threadScan.Start();
            ShowBusiness.ShowMsg("开始扫描并创建数据表");
        }

        /// <summary>
        /// 扫描并创建表
        /// </summary>
        private void AnalyseAndCreatTables()
        {
            int scantime = 10;
            while (true)
            {
                try
                {
                    //if (DateTime.Now.AddDays(2).Month != DateTime.Now.Month + 1)
                    //{

                    //    //TimeSpan exetime = new DateTime(DateTime.Now.Year, DateTime.Now.Month + 1, 1) - DateTime.Now.AddDays(2);

                    //    //ShowBusiness.ShowMsg(string.Format("当前时间【{0}】,{1}天之后执行", DateTime.Now.ToString("yyyy-MM-dd"), exetime.Days));
                    //    continue;
                    //}

                    ShowBusiness.ShowMsg("获取数据库信息");
                    // 获取数据库信息
                    BGetDataBseName getdatabaseinfo = new BGetDataBseName();
                    getdatabaseinfo.Execute();
                    List<string> databases = getdatabaseinfo.DataBases;
                    if (databases != null)
                    {
                        DateTime nowtime = Convert.ToDateTime(Factory.AppSettingFactory.GetStartTime());
                        DateTime nextMonth = nowtime.AddMonths(1);
                        foreach (var itemDatabase in databases)
                        {

                            ShowBusiness.ShowMsg(string.Format("######################开始处理【{0}】数据库YYMM #######################", itemDatabase));
                            string nowtablePostfix = nowtime.ToString("yyMM");
                            string nexttablePostfix = nextMonth.ToString("yyMM");
                            this.HandSpiltByMonth(itemDatabase, nowtablePostfix, nexttablePostfix);
                            ShowBusiness.ShowMsg(string.Format("######################处理【{0}】数据库YYMM结束#######################", itemDatabase));
                            ShowBusiness.ShowMsg(string.Format("######################开始处理【{0}】数据库YYYYMM#######################", itemDatabase));

                            nowtablePostfix = nowtime.ToString("yyyyMM");
                            nexttablePostfix = nextMonth.ToString("yyyyMM");

                            this.HandSpiltByMonth(itemDatabase, nowtablePostfix, nexttablePostfix);
                            ShowBusiness.ShowMsg(string.Format("######################处理【{0}】数据库YYYYMM结束#######################", itemDatabase));
                            ShowBusiness.ShowMsg(string.Format("######################开始处理【{0}】数据库YYYY #######################", itemDatabase));

                            nowtablePostfix = nowtime.ToString("yyyy");
                            nexttablePostfix = nextMonth.ToString("yyyy");
                            this.HandSpiltByMonth(itemDatabase, nowtablePostfix, nexttablePostfix);
                            ShowBusiness.ShowMsg(string.Format("#####################处理【{0}】数据库YYYY完成####################", itemDatabase));
                        }
                    }
                }
                catch (Exception ex)
                {
                    ShowBusiness.ShowMsg(ex.StackTrace);
                }
                finally
                {
                    Thread.Sleep(scantime * 1000 * 60 * 60);
                }
            }
        }


        /// <summary>
        /// 处理按月分表
        /// </summary>
        /// <param name="databaseName">数据库名</param>
        private void HandSpiltByMonth(string databaseName, string nowtablePostfix, string nexttablePostfix)
        {
            #region 按月分表
            // 获取该数据库中按月分表的当前月的表
            DGetTablesFromDatabase getNowDatatables = new DGetTablesFromDatabase(databaseName, nowtablePostfix);
            getNowDatatables.Execute();
            List<string> nowtablse = getNowDatatables.TablesList;
            // 获取该数据库中按月分表的下月的表
            DGetTablesFromDatabase getNextDatatables = new DGetTablesFromDatabase(databaseName, nexttablePostfix);
            getNextDatatables.Execute();
            List<string> nextDatatables = getNextDatatables.TablesList;
            // 对比当前月表和下月表，如果下月表中没有，则新建
            if (nowtablse != null && nowtablse.Count > 0)
            {
                ShowBusiness.ShowMsg(string.Format("处理【{0}】当月的表：{1}", databaseName, string.Join(",", nowtablse.ToArray())));
                ShowBusiness.ShowMsg(string.Format("处理【{0}】下月的表：{1}", databaseName, string.Join(",", nextDatatables.ToArray())));
                ShowBusiness.ShowMsg(string.Format("处理【{0}】对比当前月表和下月表", databaseName));
                foreach (var nowitem in nowtablse)
                {
                    ///基础数据库名
                    string nowbeforstr = nowitem.Substring(0, nowitem.IndexOf(nowtablePostfix));
                    // 是否已经创建
                    bool isCreated = false;
                    if (nextDatatables != null && nextDatatables.Count > 0)
                    {
                        foreach (var nextitem in nextDatatables)
                        {
                            int indexof = nextitem.IndexOf(nexttablePostfix);
                            // 基础数据库名
                            string nextbeforstr = nextitem.Substring(0, indexof);
                            if (nowbeforstr == nextbeforstr)
                            {
                                isCreated = true;
                                ShowBusiness.ShowMsg(string.Format("处理【{0}】数据库 表{1}已经创建", databaseName, nextitem));
                            }
                        }
                    }

                    // 创建下月表
                    if (!isCreated)
                    {
                        string creatTableName = nowitem.Replace(nowtablePostfix, nexttablePostfix);
                        ShowBusiness.ShowMsg(string.Format("处理【{0}】数据库 创建表{1}", databaseName, creatTableName));
                        DCreatTableFromDatabase creatTableFromDatabase = new DCreatTableFromDatabase(databaseName, nowitem, creatTableName);
                        creatTableFromDatabase.Execute();
                        int results = creatTableFromDatabase.Result;
                    }
                }
            }

            #endregion
        }
    }
}
